
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:work_tools/config/config.dart';
import 'package:work_tools/dio/api.dart';
import 'package:work_tools/widget/sheets/finished_whitelist_sheet.dart';
import './vines_state.dart';

class VinesLogic extends GetxController {
  final state = VinesState();

  @override
  void onInit() {
    super.onInit();
    loadVines();
  }

  Future<void> loadVines() async {
    try {
      final vinesStr = await api.getRedisValue(AppConfig.vinRedisKey);
      state.vines = vinesStr.toString().replaceAll(RegExp(r'\s+'), '').split(",");
      state.filterVinesRes = state.vines;
      update();
    } catch (e) {}
  }
  Future<void> filterVines(String key) async {
    state.filterKey = key.toUpperCase();
    if (key.isEmpty) {
      state.filterVinesRes = state.vines;
      update();
      return;
    }
    state.filterVinesRes = state.vines.where((e) => e.toLowerCase().contains(key.toLowerCase())).toList();
    update();
  }

  Future<void> deleteVin(String vin) async {
    final context = Get.context!;
    final redisValue = state.vines.where((e) => vin != e).toList().join(',');
    await FinishedWhitelistWidget.displaySheet(context, title: "重置 vin 码", redisKey: AppConfig.vinRedisKey, redisValue: redisValue);
    loadVines();
    return;
  }

  Future<void> addVin(String vin) async {
    final context = Get.context!;
    final redisValue = [vin, ...state.vines].join(',');
    await FinishedWhitelistWidget.displaySheet(context, title: "重置 vin 码", redisKey: AppConfig.vinRedisKey, redisValue: redisValue);
    loadVines();
    return;
  }
}